package com.example.paizhaogou;

import android.content.res.AssetManager;
import android.content.res.Resources;
import android.util.Log;

import org.tensorflow.contrib.android.TensorFlowInferenceInterface;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;

/**
 * 简化商品名字工具类
 */
public class SimplifyName {
    String itemName;
    private static String simpleName;
    TensorFlowInferenceInterface inferenceInterface;
    private String MODEL_FILE = "file:///android_asset/getProductName.pb";//模型地址
    private static HashMap<Character, Integer> wordId = new HashMap<>();  //字表
    private int[] output = new int[60 * 32]; //输出数组
    private boolean flag = false;

    public SimplifyName(String itemName) {
        this.itemName = itemName;
    }

    public String simplify(AssetManager assetManager, Resources resources) {
        initTensorFlow(assetManager);
        initData(resources);
        jdProcessResult(itemName);
        flag=true;
        return simpleName;
    }
    public  boolean isFlag(){
        return flag;
    }

    private void initTensorFlow(AssetManager assetManager) {
        inferenceInterface = new TensorFlowInferenceInterface(assetManager, MODEL_FILE);
    }

    private void initData(Resources resources) {
        try {
            InputStream inputStream = resources.openRawResource(R.raw.w2id);
            InputStreamReader inputReader = new InputStreamReader(inputStream);
            BufferedReader buffReader = new BufferedReader(inputReader);
            String line;
            while ((line = buffReader.readLine()) != null) {
                String[] lineTemp = line.split("\\s+");
                wordId.put(lineTemp[0].charAt(0), Integer.valueOf(lineTemp[1]));
            }
            inputStream.close();
        } catch (java.io.FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 数据预处理
     */
    private void jdProcessResult(String result) {
        String[] inputs = result.split("[，。！？、‘’“”（）\\(\\)]");

        int[] net_inputs = new int[32 * 60];
        Arrays.fill(net_inputs, 0);
//数组转化为字符
        for (int i = 0; i < 32; i++) {
            if (i < inputs.length) {
                char[] temp = inputs[i].toCharArray();
                for (int j = 0; j < 60; j++) {
                    if (j < temp.length) {
                        if (wordId.containsKey(temp[j])) {
                            net_inputs[i * 32 + j] = wordId.get(temp[j]);
                        } else {
                            net_inputs[i * 32 + j] = 3509;
                        }
                    }
                }
            } else {
                break;
            }
        }

        runNet(net_inputs);

        String final_result = "";
        String origin = "";

        for (int i = 0; i < inputs.length; i++) {
            origin += inputs[i];
        }

        for (int i = 0; i < 60; i++) {
            if (output[i] == 1 || output[i] == 6 || output[i] == 7 || output[i] == 17
                    || output[i] == 19 || output[i] == 21) {
                final_result += origin.charAt(i);
            }
        }
        simpleName = final_result;
        Log.e("TensorFlowDemo", "商品简化后的结果：" + final_result);
    }

    /**
     * 跑网络得输出
     */
    private void runNet(int[] inputs) {
        Arrays.fill(output, 0);
        inferenceInterface.feed("input_data:0", inputs, new long[]{32, 60}); //输入
        inferenceInterface.run(new String[]{"bilstm_crf/crf_out/ReverseSequence_1:0"}); //输出
        inferenceInterface.fetch("bilstm_crf/crf_out/ReverseSequence_1:0", output);
    }
}
